package org.project.d.network;


import org.project.d.network.msg.CommandCode;

import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author lin
 * @version V1.0
 * @description
 * @date 2020/6/16 3:50 下午
 */
public class DispatchManager {
    private static final ConcurrentMap<Short, Dispatch> cmdMDispatchs =new ConcurrentHashMap<>();
    public static CommandCode getCommandCode (short cmd){
        Dispatch dispatch = cmdMDispatchs.get(cmd);
        if (dispatch !=null){
            return dispatch.getCommandCode();
        }
        return null;
    }
    public static Dispatch getDispatch (short cmd){
        return cmdMDispatchs.get(cmd);
    }

    public static void addDispatch(Dispatch dispatch){
        short value = dispatch.getCommandCode().value();
        if (cmdMDispatchs.containsKey(value)) {
            throw new RuntimeException("cmd Dispatch map have this mapping cmd: "+value+"dispatch: "+cmdMDispatchs.get(value));
        }
        cmdMDispatchs.put(value,dispatch);
    }
    public static void addDispatch(RegisterDispatch registerDispatch){
        Dispatch.DispatchBuilder builder = Dispatch.builder();
        Dispatch dispatch = registerDispatch.Register(builder).build();
        short value = dispatch.getCommandCode().value();
        if (cmdMDispatchs.containsKey(value)) {
            throw new RuntimeException("cmd Dispatch map have this mapping cmd: "+value+"dispatch: "+cmdMDispatchs.get(value));
        }
        cmdMDispatchs.put(value,dispatch);
    }
    @FunctionalInterface
    public interface RegisterDispatch{
        Dispatch.DispatchBuilder Register(Dispatch.DispatchBuilder dispatchBuilder);
    }
}
